from django.shortcuts import render

# Create your views here.

from django.http import request,HttpResponse
from django.shortcuts import render,redirect
from index import models

import json, datetime, string
def add_user(request):
    if request.method == 'POST':
        print(request.POST)
        id = request.POST.get("id")
        name = request.POST.get("name")
        age = request.POST.get("age","a")
        print(id,name,age)

        user = models.UserInfo()
        print(user)     # UserInfo object (None)

        '''数据按条件查询'''
        # 等同于select * from user_info where name = name
        res = models.UserInfo.objects.filter(name=name)
        # 表单无对应数据时：<QuerySet []>，存在对应数据：<QuerySet [<UserInfo: UserInfo object (1002)>]>
        print(res)
        #UserInfo object (1002) <class 'index.models.UserInfo'>
        print(res[0],type(res[0]))
        # 1002 jean
        print(res[0].id,res[0].name)
        print("=" * 100)
        res_1 = models.UserInfo.objects.filter(name=name).first()
        print(res_1)    # UserInfo object (1002)
        print(res_1.name,res_1.id)      # jean 1002
    return render(request,"add_user.html")

def login(request):
    '''数据查询'''
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        res = models.User.objects.filter(username=username)
        print(res)
    return render(request,"login.html")

def reg(request):
    '''数据库增加'''
    # 方式一
    # if request.method == "POST":
    #     #     username = request.POST.get("username")
    #     #     password = request.POST.get("password")
    #     #     res = models.User.objects.create(username=username,password=password)
    #     #     # User object (2) jean 123456
    #     #     print(res,res.username,res.password)
    # 方式二
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user_obj = models.User(username=username,password=password)
        user_obj.save()
    return render(request,"reg.html")

def user_list(request):
    '''数据查询'''
    # 方式一
    data = models.User.objects.filter()
    '''
    <QuerySet [<User: User object (1)>, <User: User object (2)>]>
    User object (1)
    jean
    123456   
    '''
    print(data,data[0],data[0].username,data[0].password,sep="\n")

    # 方式二
    user_info = models.User.objects.all().order_by("id")[0:20]
    print(user_info)
    # return render(request,"user_list.html",{"user_info":user_info})
    # locals()作用在于编辑html文件时，会出现提示
    return render(request,"user_list.html",locals())

def edit_user(request):
    ''''数据编辑'''
    # 方式一
    # 推荐使用
    # user_id = request.GET.get("user_id")
    # if request.method == "POST":
    #     username = request.POST.get("username")
    #     password = request.POST.get("password")
    #     models.User.objects.filter(id=user_id).update(username=username,password=password)
    #     return redirect("/user_list/")
    #
    # edit_obj = models.User.objects.filter(id=user_id).first()
    # print(edit_obj)
    # return render(request,"edit_user.html",locals())

    # 方式二
    # 将所有的字段都更新一遍
    user_id = request.GET.get("user_id")
    edit_obj = models.User.objects.filter(id=user_id).first()
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        edit_obj.username = username
        edit_obj.password = password
        edit_obj.save()
        return redirect("/user_list/")
    return render(request,"edit_user.html",locals())

def del_user(request):
    '''数据库删除'''
    user_id = request.GET.get("user_id")
    models.User.objects.filter(id=user_id).delete()
    return redirect("/user_list/")

def index(request):
    return HttpResponse("welcome")

def welcome(request):
    '''
    http://127.0.0.1:8000/welcome/?user=cat
    request: <WSGIRequest: GET '/welcome/'>
    request.path: url路径，/welcome/
    '''
    if request.method == "GET":
        user = request.GET.get("user","human")
        return HttpResponse(f"welcome {user}.\n{request}\n{request.path}")
    elif request.method == "POST":
        name = request.POST.get("name","kid")
        # request.body用于POST方法，返回二进制字节流 b'name=cat'
        return HttpResponse(f"welcome {name}.\n{request.body}")

def add_user_simple(request):
    user = models.User(username="admin01",password=258)
    user.save()
    user = models.User.objects.create(username="admin02")
    return HttpResponse("creat")

def ret_user_simple(request):
    '''
    <QuerySet [<User: User object (1)>, <User: User object (2)>... <User: User object (15)>]>
    User object (1)
    User object (15)
    jean
    cat
    '''
    users = models.User.objects.filter()
    users = models.User.objects.all()       # 效果同上
    print(users,users.first(),users.last())
    for user in users[:2]:
        print(user.username)

    # pk表示primary key主键，不存在报错
    user_1 = models.User.objects.filter(pk=12)
    print(user_1[0].username)

    # exclude不包含，user表中2处地方username=jam，都已进行过滤
    user_2 = models.User.objects.exclude(username="jam")
    for user in user_2:
        print(user.username)

    '''
    只有一个条件符合情况下用get(),多个条件满足报错
    get()和filter()区别:前者是一个元素，后面是列表
    User object (2)     <QuerySet [<User: User object (2)>]>
    '''
    user_3 = models.User.objects.get(username="cat")
    user_4 = models.User.objects.filter(username="cat")
    print(user_3,user_4)
    # 反序查询
    print(models.User.objects.order_by("username").reverse())

    # 查询指定字段，不存在字段报错，列表元素为字典：{'username': 'jean', 'password': '123456'}{'username': 'cat', 'password': '8800'}
    user_5 = models.User.objects.values("username","password")

    # 查询指定字段，列表元素为元组：('jean', '123456')('cat', '8800')
    user_6 = models.User.objects.values_list("username","password")
    return HttpResponse(user_5)

def update_user_simple(request):
    user = models.User.objects.filter(username="susan").first()
    user.password = "sq25800"
    # save()只能更新一个对象
    user.save()
    # 对于多个满足条件的值，可以逐个设置
    user_one = models.User.objects.filter(username="jam")[0]
    user_one.password = "jam16800"
    user_one.save()
    return HttpResponse(user)

